<template>
  <view class="container">
    <intake-nav-bar title="设备列表" dark :fixed="true" />
    <!-- 设备列表 -->
    <scroll-view scroll-y="true" style="height: 100vh;" @scrolltolower="loadMore">
         <view class="list-fb" @click.stop="newFun"> 查看列表分布</view>
         <view class="device-list">
           <view v-for="(item, index) in list" :key="index" class="device-card">
             <view class="card-left">
               <view class="device-name">{{ item.title }}</view>
               <view class="device-address">{{ item.address }}</view>
               <view class="device-distance">距离{{ item.distance }}</view>
               <!-- <text class="link-text">查看设备图片</text> -->
             </view>
             <view class="card-right" @click.stop="handleNavigation(item)">
               <view class="nav-box">
                 <uni-icons type="location" size="36" color="#0066FF" />
                 <text class="nav-text">导航设备位置</text>
               </view>
             </view>
           </view>
         </view>
         <view v-if="loading" class="loading">加载中...</view>
         <view v-if="noMore" class="no-more">没有更多数据了</view>
       </scroll-view>
w  </view>
</template>
<script>
import { queryMapList } from '@/api/water';
import { mapGetters } from 'vuex';
export default {

  data() {
    return {
      list: [], // 列表数据
      page: 1, // 当前页码
      pageSize: 10, // 每页数据量
      loading: false, // 是否正在加载
      noMore: false, // 是否没有更多数据
      // 目标纬度
      latitude: '',
      // 目标经度
      longitude: '',
      // 目标地址名称
      name: '',
      // 目标地址详细信息
      address: '',
      // 我自己的位置经纬度（百度地图需要传入自己的经纬度进行导航）
      selfLocation: {
        latitude: '',
        longitude: ''
      },
    };
  },
  onLoad() {
    this.getLocation()
  },
  methods: {
    newFun(){
      this.$common.navTo('/pages/intake/device/map');

    },
    // 查看设备分布
    handleClickRight(){
      this.$common.navTo('/pages/intake/device/index');
    },
    async queryList() {
      if (this.loading || this.noMore) return;
      this.loading = true;
      console.log(typeof(this.latitude.toString()))
      const newData = await queryMapList(
        {
          page: this.page,
          pageSize: this.pageSize,
          lat:this.latitude.toString(),
          lng:this.longitude.toString(),
        })
      if (newData.data.data.length > 0) {
        this.list = this.list.concat(newData.data.data);
        this.page++;
      } else {
        this.noMore = true;
      }

      this.loading = false;
    },
    // 模拟异步请求
    fetchData(page, pageSize) {
      return new Promise((resolve) => {
        setTimeout(() => {
          const data = queryMapList(
            {
              page: page,
              pageSize: pageSize
            })
          resolve(data.data.data);
        }, 1000);
      });
    },
    // 加载更多
    loadMore() {
      this.queryList();
    },
    // 获取当前位置
    getLocation() {
      uni.getLocation({
        type: 'wgs84', // 返回GPS经纬度
        success: (res) => {
          this.latitude = res.latitude;
          this.longitude = res.longitude;
          this.queryList()
        },
        fail: (err) => {
          console.error('获取位置失败:', err);
          uni.showToast({
            title: '获取位置失败',
            icon: 'none',
          });
        },
      });
    },
    // 打开地图去导航
    handleNavigation(item) {
      const _this = this
      if (!item.lat || !item.lng || !item.title) return
      // 微信
      // #ifdef MP-WEIXIN
      let _obj = {
        latitude: parseFloat(item.lat),
        longitude: parseFloat(item.lng),
        name: item.title,
      }
      if (this.address) {
        _obj['address'] = item.address
      }
      uni.openLocation({
        ..._obj,
        success: function (res) {
          console.log('打开系统位置地图成功',res)
        },
        fail: function (error) {
          console.log(error)
        }
      })
      // #endif

      // #ifdef APP-PLUS
      // 判断系统安装的地图应用有哪些, 并生成菜单按钮
      let _mapName = [
        { title: '高德地图', name: 'amap', androidName: 'com.autonavi.minimap', iosName: 'iosamap://' },
        { title: '百度地图', name: 'baidumap', androidName: 'com.baidu.BaiduMap', iosName: 'baidumap://' },
        { title: '腾讯地图', name: 'qqmap', androidName: 'com.tencent.map', iosName: 'qqmap://' },
      ]
      // 根据真机有的地图软件 生成的 操作菜单
      let buttons = []
      let platform = uni.getSystemInfoSync().platform
      platform === 'android' && _mapName.forEach(item => {
        if (plus.runtime.isApplicationExist({ pname: item.androidName })) {
          buttons.push(item)
        }
      })
      platform === 'ios' && _mapName.forEach(item => {
        console.log(item.iosName)
        if (plus.runtime.isApplicationExist({ action: item.iosName })) {
          buttons.push(item)
        }
      })
      if (buttons.length) {
        plus.nativeUI.actionSheet({ //选择菜单
          title: "选择地图应用",
          cancel: "取消",
          buttons: buttons
        }, function (e) {
          let _map = buttons[e.index - 1]
          _this.openURL(_map, platform)
        })
      } else {
        uni.showToast({
          title: '请安装地图软件',
          icon: 'none'
        })
        return
      }
      // #endif
    },
    // 打开第三方程序实际应用
    openURL(map, platform) {
      let _defaultUrl = {
        android: {
          "amap": `amapuri://route/plan/?sid=&did=&dlat=${this.latitude}&dlon=${this.longitude}&dname=${this.name}&dev=0&t=0`,
          'qqmap': `qqmap://map/routeplan?type=drive&to=${this.name}&tocoord=${this.latitude},${this.longitude}&referer=fuxishan_uni_client`,
          'baidumap': `baidumap://map/direction?origin=${this.selfLocation.latitude},${this.selfLocation.longitude}&destination=name:${this.name}|latlng:${this.latitude},${this.longitude}&coord_type=wgs84&mode=driving&src=andr.baidu.openAPIdemo"`
        },
        ios: {
          "amap": `iosamap://path?sourceApplication=fuxishan_uni_client&dlat=${this.latitude}&dlon=${this.longitude}&dname=${this.name}&dev=0&t=0`,
          'qqmap': `qqmap://map/routeplan?type=drive&to=${this.name}&tocoord=${this.latitude},${this.longitude}&referer=fuxishan_uni_client`,
          'baidumap': `baidumap://map/direction?origin=${this.selfLocation.latitude},${this.selfLocation.longitude}&destination=name:${this.name}|latlng:${this.latitude},${this.longitude}&mode=driving&src=ios.baidu.openAPIdemo`
        }
      }
      let newurl = encodeURI(_defaultUrl[platform][map.name]);
      plus.runtime.openURL(newurl, function (res) {
        uni.showModal({
          content: res.message
        })
      }, map.androidName ? map.androidName : '');
    }
  }
}
</script>

<style lang="scss">
.container {
  width: 100%;
  height: 100vh;
  // padding: 20px;
  background: linear-gradient(to bottom, #E3EAFB 0%, transparent 100%);
}

.container {
  min-height: 100%;
  background-color: #FFFFFF;
  padding: 0 32rpx;
}
.list-fb{
  float: right;
  color: #034EFD;
  margin-bottom: 10rpx;
}
.header {
  display: flex;
  align-items: center;
  height: 88rpx;
  position: relative;
}

.header-left {
  width: 44rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-title {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.header-right {
  position: absolute;
  right: 0;
}

.link-text {
  color: #0066FF;
  font-size: 14px;
}

.device-list {
  padding: 20rpx 0;

}

.device-card {
  width: 100%;
  margin-bottom: 20rpx;
  border: 1px dashed #DDDDDD;
  border-radius: 12rpx;
  padding: 24rpx;
  display: flex;
  justify-content: space-between;
  background-color: #fff;
}

.card-left {
  flex: 1;
}

.device-name {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
  margin-bottom: 16rpx;
}

.device-address {
  width: 400rpx;
  font-size: 14px;
  color: #666666;
  margin-bottom: 8rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.device-distance {
  font-size: 14px;
  color: #666666;
  margin-bottom: 16rpx;

}

.card-right {
  border-left: 1px dashed #ccc;
  display: flex;
  align-items: center;
  // margin-left: 20rpx;
  padding: 0 23rpx;
}

.nav-box {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.nav-text {
  font-size: 12px;
  color: #0066FF;
  margin-top: 8rpx;
}
</style>
<style>
.loading,
.load-more,
.no-more {
  text-align: center;
  padding: 20px;
  font-size: 14px;
  color: #666;
}
</style>
